package com.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Map;
import java.util.HashMap;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;

import com.utils.ValidatorUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.annotation.IgnoreAuth;

import com.entity.KanjiaEntity;
import com.service.KanjiaService;
import com.service.ErshoushangpinService;
import com.entity.ErshoushangpinEntity;
import com.utils.PageUtils;
import com.utils.R;
import com.utils.MPUtil;

/**
 * 砍价信息
 * 后端接口
 * @author 
 * @email 
 * @date 2025-09-11
 */
@RestController
@RequestMapping("/kanjia")
public class KanjiaController {
    @Autowired
    private KanjiaService kanjiaService;

    @Autowired
    private ErshoushangpinService ershoushangpinService;

    /**
     * 后端列表
     */
    @RequestMapping("/page")
    public R page(@RequestParam Map<String, Object> params, KanjiaEntity kanjia, 
                  HttpServletRequest request){
        String tableName = request.getSession().getAttribute("tableName").toString();
        if(tableName.equals("chiwuzhe")) {
            kanjia.setChiwuzhanghao((String)request.getSession().getAttribute("username"));
        }
        if(tableName.equals("yonghu")) {
            kanjia.setYonghuming((String)request.getSession().getAttribute("username"));
        }
        
        EntityWrapper<KanjiaEntity> ew = new EntityWrapper<KanjiaEntity>();
        PageUtils page = kanjiaService.queryPage(params, MPUtil.sort(MPUtil.between(MPUtil.likeOrEq(ew, kanjia), params), params));

        return R.ok().put("data", page);
    }
    
    /**
     * 前端列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params, KanjiaEntity kanjia, 
                  HttpServletRequest request){
        EntityWrapper<KanjiaEntity> ew = new EntityWrapper<KanjiaEntity>();
        PageUtils page = kanjiaService.queryPage(params, MPUtil.sort(MPUtil.between(MPUtil.likeOrEq(ew, kanjia), params), params));
        return R.ok().put("data", page);
    }

    /**
     * 查询详情
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id){
        KanjiaEntity kanjia = kanjiaService.selectById(id);
        return R.ok().put("data", kanjia);
    }

    /**
     * 获取参考价格
     */
    @RequestMapping("/getReferencePrice")
    public R getReferencePrice(@RequestParam("shangpinId") Long shangpinId) {
        // 根据商品ID获取商品信息
        ErshoushangpinEntity shangpin = ershoushangpinService.selectById(shangpinId);
        if (shangpin == null) {
            return R.error("商品不存在");
        }
        
        String referencePrice = kanjiaService.getReferencePrice(shangpin.getShangpinmingcheng(), shangpin.getWupinfenlei());
        return R.ok().put("referencePrice", referencePrice);
    }

    /**
     * 提交砍价
     */
    @RequestMapping("/save")
    public R save(@RequestBody KanjiaEntity kanjia, HttpServletRequest request){
        // 获取当前登录用户信息
        String tableName = request.getSession().getAttribute("tableName").toString();
        if ("yonghu".equals(tableName)) {
            kanjia.setYonghuming((String)request.getSession().getAttribute("username"));
            kanjia.setYonghuid((Long)request.getSession().getAttribute("userId"));
        }
        
        // 获取商品信息
        ErshoushangpinEntity shangpin = ershoushangpinService.selectById(kanjia.getShangpinid());
        if (shangpin != null) {
            kanjia.setShangpinmingcheng(shangpin.getShangpinmingcheng());
            kanjia.setYuanjia(shangpin.getPrice());
            kanjia.setChiwuzhanghao(shangpin.getChiwuzhanghao());
            
            // 获取参考价格说明和实际参考价格
            String referencePrice = kanjiaService.getReferencePrice(shangpin.getShangpinmingcheng(), shangpin.getWupinfenlei());
            kanjia.setCankaojiage(referencePrice);
            
            // 计算砍价价格：参考市场均价，但确保不会越砍越贵
            if (kanjia.getKanjiajia() == null && shangpin.getPrice() != null) {
                Float kanjiaPrice = kanjiaService.calculateKanjiaPrice(shangpin.getShangpinmingcheng(), shangpin.getWupinfenlei(), shangpin.getPrice());
                kanjia.setKanjiajia(kanjiaPrice);
                
                // 添加调试信息（可选，生产环境可删除）
                System.out.println("砍价计算 - 商品: " + shangpin.getShangpinmingcheng() + 
                                 ", 原价: " + shangpin.getPrice() + 
                                 ", 砍价后: " + kanjiaPrice);
            }
        }
        
        kanjia.setStatus("待处理");
        // 设置添加时间
        kanjia.setAddtime(new Date());
        kanjiaService.insert(kanjia);

        return R.ok();
    }

    /**
     * 修改砍价状态（持书人同意砍价）
     */
    @RequestMapping("/updateStatus")
    @Transactional
    public R updateStatus(@RequestParam("id") Long id, 
                         @RequestParam("status") String status,
                         @RequestParam(value = "beizhu", required = false) String beizhu,
                         HttpServletRequest request) {
        
        KanjiaEntity kanjia = kanjiaService.selectById(id);
        if (kanjia == null) {
            return R.error("砍价记录不存在");
        }
        
        // 只有持书人可以处理砍价请求
        String tableName = request.getSession().getAttribute("tableName").toString();
        String username = (String)request.getSession().getAttribute("username");
        if (!"chiwuzhe".equals(tableName) || !kanjia.getChiwuzhanghao().equals(username)) {
            return R.error("无权限处理此砍价请求");
        }
        
        kanjia.setStatus(status);
        kanjia.setBeizhu(beizhu);
        kanjiaService.updateById(kanjia);
        
        // 如果同意砍价，更新商品价格
        if ("已同意".equals(status)) {
            ErshoushangpinEntity shangpin = ershoushangpinService.selectById(kanjia.getShangpinid());
            if (shangpin != null) {
                shangpin.setPrice(kanjia.getKanjiajia());
                ershoushangpinService.updateById(shangpin);
            }
        }
        
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] ids){
        kanjiaService.deleteBatchIds(Arrays.asList(ids));
        return R.ok();
    }
} 